<?php

class Application_Model_AclRights extends Zend_Db_Table {
	protected $_name = 'acl_rights';
	protected $_primary = array('acl_role_id', 'acl_resource_id');
	protected $_sequence = true;
	
	public function getAclValues($conditions) {
		$sql = $this->select();
		
		if ($conditions) {
			if (is_array($conditions)) {
				foreach($conditions as $k => $v) {
					$sql->where($k, $v);
				}
			} else {
				$sql->where($conditions);
			}
		}
		return $this->fetchAll($sql);
	}
	/**
	 * Intoarce drepturile de acces ale grupului $roleName pe resurse
	 *
	 * @param string $roleName
	 * @return mixed
	 */
	public function getRightsForRole( $_roleName , $_roleParent = null ) {

		$modelAclResources = new Application_Model_AclResources();
		$arrResources = $modelAclResources->getAclResources();
		//Zend_Debug::dump($arrResources);exit;

		$cache = Zend_Registry::get('Zend_Cache_Core');
		$modelAcl = $cache->load('ACL_rights');
		$roleId = Application_Model_AclRole::getRoleIdByName( $_roleName );

		$rightsForRole = $this->getRightsRecords( $roleId );

		$arrResult = array();
		foreach ( $arrResources as $resource ){
			$arrResult[$resource['id']] = array(
				'id'			=> $resource['id'],
				'name'			=> $resource['resource'],
				'checked_right' => (array_key_exists($resource['id'], $rightsForRole) && $rightsForRole[$resource['id']]) ? ' checked="checked"':'',
				'checked_deny'	=> (array_key_exists($resource['id'], $rightsForRole) && $rightsForRole[$resource['id']] == 0 ) ? ' checked="checked"':''
			);
			if ( $_roleParent ){
				$arrResult[$resource['id']]['checked_inherit'] =  '';
				if ( !array_key_exists($resource['id'], $rightsForRole) ){
					$arrResult[$resource['id']]['checked_inherit'] =  ' checked="checked"';							
				}
				
				$arrResult[$resource['id']]['checked_parent_right'] = $modelAcl->isAllowed( $_roleParent, $resource['resource'] ) ? ' checked="checked"':'';
			}
		}

		return $arrResult;
	}


	public function getRightsForRoleId( $_roleId ) {
		$sql = $this->select()->setIntegrityCheck(false)
					->from(array('a' => $this->_name), array('permission'))
					->join(array('b' => 'acl_resource'), 'a.acl_resource_id=b.id', array('resource'=>'resource'))
					->where('a.acl_role_id = ?', $_roleId);

		$result = $this->getAdapter()->fetchAll($sql);

		return $result;
	}

	public function getRightsRecords( $_roleId ){
		$sql = $this->select()->setIntegrityCheck(false)
					->from($this->_name, array('acl_resource_id', 'permission'))
					->where('acl_role_id = ?', $_roleId);

		$result = $this->getAdapter()->fetchPairs($sql);

		return $result;
	}
}
